package com.xuecheng.search.listener;

import com.xuecheng.search.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 消息监听器：指定自动获取消息之后的处理业务
 * 1、类交给容器管理
 * 2、配置方法（没有返回值，参数和发送端消息类型一致）
 * 3、方法上配置注解@RabbitListener
 */
@Component
@Slf4j
public class MessageListener {


    @Autowired
    private SearchService searchService;

    //配置交换机，队列的绑定关系
    @RabbitListener(
        bindings = @QueueBinding(
                value = @Queue(
                        value = "course.index.queue"
                ),
                exchange = @Exchange(
                        value = "content-exchange",
                        type = ExchangeTypes.TOPIC
                ),
                key = "course.pub"
        )
    )
    public void listener(Long coursePubId) {
        //更新索引（下次课）
        log.info("获取MQ消息：coursePubId="+coursePubId);
        //同步es索引库
        try {
            searchService.updateIndex(coursePubId);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
